#!/bin/bash

############################################################################
#
# 在终端（粘贴）执行如下命令，可远程执行该脚本：
#
#   curl -sSL https://gitee.com/tay3223/biubiubiu/raw/master/script-prometheus/centos7-install-process_exporter.sh | /bin/bash
#
############################################################################

BinaryFileUrl="https://osoc.oss-cn-shanghai.aliyuncs.com/bao/prometheus/BinaryFile/process-exporter-0.7.5.linux-amd64/process-exporter" #二进制文件的URL
BinaryFileName="process_exporter"                                                                                                               #二进制文件的名称（可以修改，不需要与云端的文件原名保持一致）
RunPort="9256"                                                                                                                                  #运行起来后监听的端口号
ConfigUrl="https://osoc.oss-cn-shanghai.aliyuncs.com/bao/prometheus/BinaryFile/process-exporter-0.7.5.linux-amd64/conf.yaml"            #配置文件内容（并不是所有的组件运行时都需要配置文件的）

#安装exporter
function install_exporter() {
    mkdir -p /opt/monitoring/${BinaryFileName}                                   #创建工作目录
    wget ${BinaryFileUrl} -O /opt/monitoring/${BinaryFileName}/${BinaryFileName} #下载二进制文件到指定位置，并完成重命名
    chmod +x /opt/monitoring/${BinaryFileName}/${BinaryFileName}                 #授予可执行权限
    /opt/monitoring/${BinaryFileName}/${BinaryFileName} --version                #查看版本
    wget ${ConfigUrl} -O /opt/monitoring/${BinaryFileName}/conf.yaml             #下载配置文件到指定位置，并完成重命名（并不是所有组件都需要下载配置文件的，注意区分）
}

#注册守护进程
function register_daemons() {
    local SERVICE_PATH="/usr/lib/systemd/system/${BinaryFileName}.service"
    cat <<EOF >${SERVICE_PATH}
[Unit]
Description=${BinaryFileName}
After=network.target


[Service]
Type=simple
User=root
Group=root
LimitNOFILE=100000
LimitNPROC=100000
ExecStart=/opt/monitoring/${BinaryFileName}/${BinaryFileName} --config.path=/opt/monitoring/${BinaryFileName}/conf.yaml
Restart=no


[Install]
WantedBy=multi-user.target
EOF

    chmod 644 ${SERVICE_PATH}
    systemctl daemon-reload
    systemctl enable ${BinaryFileName}.service
}

#打印帮助信息
function help() {
    cat <<EOF

===================================

[√]  1.${BinaryFileName} 守护进程已注册
[√]  2.${BinaryFileName} 开机启动已完成
[√]  3.${BinaryFileName} 运行端口为：${RunPort}


#重新加载systemctl服务器
systemctl daemon-reload

#常用命令
systemctl start   ${BinaryFileName}.service
systemctl status  ${BinaryFileName}.service
systemctl stop    ${BinaryFileName}.service
systemctl restart ${BinaryFileName}.service
systemctl enable  ${BinaryFileName}.service

===================================

EOF
}

######################################################
# main()
######################################################
#关闭已有的守护进程
if (systemctl stop ${BinaryFileName}.service); then
    echo -e "\n守护进程关闭成功\n"
else
    echo -e "\n守护进程不存在，无需关闭\n"
fi

#调用函数
install_exporter
register_daemons
help
